#!/usr/bin/env python
# -*- coding: utf-8 -*-
#

from celtuce import Storer, KEY_MIN, KEY_MAX, RC_TIMEOUT

import os,os.path,tempfile,time

import celtuce.help.logging as logging

PATH = os.sep.join((tempfile.gettempdir(), 'celtuce/hello'))

TABLE = 'hellosplit'


class   TestSplit(object) :
    def setUp(self) :
        logger = logging.getLogger()
        #logger.setLevel(logging.LEVEL_DEBUG)

        if os.path.exists(PATH) :
           self.removedirs(PATH)

        os.makedirs(PATH, 0777)

        self.storer = Storer()
        self.storer.startup( PATH )

        response = self.storer.createTablet( TABLE, KEY_MIN, KEY_MAX )
        if not response.isOk() :
            self.storer.shutdown()
            print response.status_code,response.error
            raise RuntimeError, response.error
        ## setUp()

    def tearDown(self) :
        self.storer.shutdown()
        ## tearDown()

    def removedirs(self, path) :
        items = os.listdir(path)
        for name in items :
            fullpath = os.sep.join((path, name))
            if os.path.isdir(fullpath) :
                self.removedirs(fullpath)
            else :
                os.remove(fullpath)

        os.rmdir(path)
        ## removedirs

    def run(self) :
        K = 1024
        M = 1024 * 1024
        G = 1024 * 1024 * 1024

        block_size = 1024 * K
        data_size = 5 * G
        try :
            t.setUp()
            self.feedData(data_size, block_size)
        finally :
            t.tearDown()
        ## run()

    ####-----------------------------------------------------------####

    def feedData(self, data_size, block_size=1048576) :
        data_chunk = 'A' * block_size
        len_data_chunk = len(data_chunk)
        sum = 0
        index = 0
        time_start = time.time()
        try :
            while sum < data_size :
                key = '-'.join(('hello',str(index)))
                value = '-'.join(('world',str(index),data_chunk))
                for retry in (1,2,3) :
                    response = self.storer.insert(TABLE, key, value, 12345678)
                    if response.isOk() :
                        break
                    elif response.status_code == RC_TIMEOUT :
                        if retry < 3 :
                            time.sleep(1)
                            continue
                        else :
                            raise RuntimeError, response.error
                    else :
                        raise RuntimeError, response.error
                index += 1
                sum += len_data_chunk
        finally :
            time_last = time.time() - time_start
            tps = index / time_last
            bw  = sum / time_last / 1048576
            print 'insert %d records (block-size:%.2f KB, volumn:%.2f MB) last %.2f seconds, TPS=%.2f BW=%.2f MB/s' % (index, block_size/1024.0, sum/1048576.0, time_last, tps, bw)
        max_index = index 
        
        sum = 0
        index = 0
        time_start = time.time()
        try :
            for index in xrange(max_index) :
                key = '-'.join(('hello',str(index)))
                value = '-'.join(('world',str(index),data_chunk))
                response = self.storer.find(TABLE, key)
                if not response.isOk() :
                    raise RuntimeError, response.error
                if not response.body :
                    raise RuntimeError, 'bad data of %s in table "%s"' % (key, TABLE)
                assert response.body[3] == value
                sum += len(value)
            index = max_index
        finally :
            time_last = time.time() - time_start
            tps = index / time_last
            bw  = sum / time_last / 1048576
            print 'find   %d records (block-size:%.2f KB, volumn:%.2f MB) last %.2f seconds, TPS=%.2f BW=%.2f MB/s' % (index, block_size/1024.0, sum/1048576.0, time_last, tps, bw)
            
        ## feedData()

    ## TestSplit()

if  __name__ == '__main__' :
    t = TestSplit()
    t.run()

